/*
 * @Author: Klein
 * @Date: 2021-06-17 15:21:58
 * @Description: file content
 */

const jwt = require("jsonwebtoken");
const secret = "Klein";
const Message = require("../lib/message");
const { WHITE_LIST } = require("../config/index");
/**
 * @description: 通过jwt将身份标识的数据字段+密钥+过期时间生成token
 * @param {Object} data - 身份标识
 * @return {String} token
 */
const tokenGet = (data) => jwt.sign(data, secret, { expiresIn: "7day" });

/**
 * @description: 对token进行校验，验证token的信息以及过期时间
 * @param {String} token
 * @return {Object} 解析出来的token数据以及过期时间exp 跟签名时间iat
 */
const tokenVerify = (token) => jwt.verify(token, secret);

const koaJwt = async (ctx, next) => {
  const url = WHITE_LIST;
  if (url.includes(ctx.request.url)) {
    await next();
  } else {
    const token = ctx.request.headers["x-token"] || "";
    if (!token) return (ctx.body = Message.error(401, "没有权限访问"));
    const decode = tokenVerify(token);
    ctx.state.jwtdata = decode;
    await next();
  }
};

module.exports = {
  tokenGet,
  tokenVerify,
  secret,
  koaJwt,
};
